package com.qingyun.customview.bezier.cart

import android.animation.ValueAnimator
import android.graphics.Path
import android.graphics.PathMeasure
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageView
import androidx.core.animation.addListener
import com.qingyun.customview.R

class CartAnimUtils {
    companion object {
        fun startCartAnim(
            startView: View,
            endView: View,
            parentView: ViewGroup,
            duration: Long = 1000,
        ) {
            val animView = ImageView(parentView.context).apply {
                setImageResource(R.drawable.ic_add_circle_outline)
            }
            parentView.addView(animView)

            //获取起点，终点坐标
            val startLocation = IntArray(2)
            startView.getLocationInWindow(startLocation)
            val endLocation = IntArray(2)
            endView.getLocationInWindow(endLocation)
            //计算起点，终点坐标
            val startX = startLocation[0].toFloat()
            val startY = startLocation[1].toFloat()
            val endX = endLocation[0].toFloat()
            val endY = endLocation[1].toFloat()

            val controlX = (startX + endX) / 2
            val controlY = startY

            val path = Path()
            path.moveTo(startX, startY)
            path.quadTo(controlX, controlY, endX, endY)

            val pathMeasure = PathMeasure(path, false)
            ValueAnimator.ofFloat(0f, pathMeasure.length).apply {
                this.duration = duration
                this.interpolator = LinearInterpolator()
                this.addUpdateListener {
                    val value = it.animatedValue as Float
                    val pos = FloatArray(2)
                    pathMeasure.getPosTan(value, pos, null)
                    animView.translationX = pos[0]
                    animView.translationY = pos[1]
                }
                this.addListener(
                    onEnd = {
                        parentView.removeView(animView)
                    }
                )
            }.also {
                it.start()
            }
        }
    }
}